import { ReactElement, useState, useRef } from 'react'
import Search, { formatCondition } from './components/search'
import style from './index.module.less'
import Table, { TableRef } from '@components/table'
import { getListQuest } from './ajax'
import { ArbitratorStatisticSchema } from '@components/schema/arbitrator'
import { ConditionSchema } from '@components/schema/condition'
import { awaitWrap } from '@js/tool'
import { getColumn } from './util'

// 初始化数据
async function initData (data: { [k: string]: any}, setDataSource: (v: ArbitratorStatisticSchema[]) => void, setTotal: (v: number) => void, setLoading: (v: boolean) => void): Promise<void> {
  setLoading(true)
  const formData: { [k: string]: any } = {
    condition: JSON.stringify(formatAllCondition(data)),
    page: data.page,
    limit: data.limit
  }
  if (typeof data.order_field === 'string' && typeof data.order === 'string') {
    formData.order_field = data.order_field
    formData.order = data.order
  }
  const [e, d] = await awaitWrap(getListQuest(formData))
  setLoading(false)
  if (e === null && d !== null) {
    setTotal(d.total)
    setDataSource(d.list)
  }
}

// 格式化搜索条件
function formatAllCondition (o: { [k: string]: any }): ConditionSchema[] {
  const condition = formatCondition(o)
  return condition
}

function Main (): ReactElement {
  const tableRef = useRef<TableRef>(null)
  const [loading, setLoading] = useState(false)
  const [total, setTotal] = useState(0)
  const [dataSource, setDataSource] = useState<ArbitratorStatisticSchema[]>([])
  const [params, setParams] = useState<{[k: string]: any}>({})
  return (
    <div className={style.container}>
      <div className={style.search}>
        <Search params={params} setParams={setParams} />
      </div>
      <div className={style.table}>
        <Table ref={tableRef} params={params} setParams={setParams} rowKey='orderno' columns={getColumn()} loading={loading} total={total} dataSource={dataSource} onChange={async (d) => {
          await initData(d, setDataSource, setTotal, setLoading)
        }} />
      </div>
    </div>
  )
}

export default Main
